<template>
    <div>
        <div class="search">
            <!-- 搜索区 -->
            <el-input placeholder="请输入内容" v-model="queryModel.query" class="input-with-select" style="width:50%;">
                <el-button :loading="loading" @click="queryModel.pagenum = 1; searchUser()" slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-button class="add" type="primary" @click="addModel = {}; dialogFormVisible = true">添加用户</el-button>
        </div>
        <!-- 列表 -->
        <Table 
        :total="total" 
        v-model="queryModel" 
        @change = 'searchUser' 
        :data="list" 
        :cols="cols"
        >
            <template v-slot:state="{ row }">
                <el-switch v-model="row.mg_state" @change="value => changeState(row,value)"></el-switch>
            </template>
            <!-- 操作 -->
            <template v-slot:action = "{row}">
                <el-button size="mini" type="primary" @click="addModel = {...row}; dialogFormVisible =true; ">编辑</el-button>
                <el-button size="mini" type="warning" @click="delUser(row)">删除</el-button>
                <el-button size="mini" type="warning" :loading = roleLoading @click=" addModel =  {...row};assignVisible = true; getRoleList();">分配角色</el-button>
            </template>
        </Table>

        <!-- 分页 -->
         <!-- <el-pagination
            @size-change="(size) => {queryModel.pagesize = size;searchUser();}"
            @current-change="(num) => {queryModel.pagenum = num;searchUser();}"
            :current-page="queryModel.pagenum"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="queryModel.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination> -->

        <!-- 添加 -->
        <el-dialog :close-on-click-modal = "false" :title="isAdd ? '添加数据' : '编辑数据'" :visible.sync="dialogFormVisible">
        <el-form ref='form' inline :model="addModel" :rules="rules">
            <el-form-item label="用户名" prop="username">
            <el-input :disabled="!isAdd" :maxlength="10" v-model="addModel.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" v-if="isAdd" prop="password">
            <el-input type="password" :maxlength="16" v-model="addModel.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input :maxlength="20" v-model="addModel.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
            <el-input :maxlength="11" v-model="addModel.mobile"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" :loading="addLoading" @click="addUser()">确 定</el-button>
        </div>
        </el-dialog> 
        <!-- 分配角色 -->
        <el-dialog :close-on-click-modal = "false" title="分配角色" :visible.sync="assignVisible">
            <p>
                当前的用户：{{addModel.username}}
            </p>
             <p>
                当前的角色：{{addModel.role_name}}
            </p>
            <p>
                分配新角色：<el-select placeholder="请选择角色" 
                v-model="addModel.role_name">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
            </p>
            <div slot="footer" class="dialog-footer">
                <el-button @click="assignVisible = false">取 消</el-button>
                <el-button type="primary" :loading="addLoading" @click="assignUserRole">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {search,switchState,user,update,deleteUser,assignRole} from '@/api/user'
import {getRoles, } from '@/api/role'
const cols = [
    {
        title:'#',
        type:"index"
    }, 
    {
        title:'姓名',
        name:'username'
    },
    {
        title:'邮箱',
        name:'email'
    },
    {
        title:'电话',
        name:'mobile'
    },
    {
        title:'角色',
        name:'role_name'
    },
    {
        title:'状态',
        slot:'state',
        width:80
    },
    {
        title:'操作',
        slot:'action',
        align:'center',
        width:240
    }
];

export default {
    name:"UserList",
    data() {
        return {
            queryModel:{
                query:'',
                pagenum:1,
                pagesize:10
            },
            list:[],
            total:0,
            dialogFormVisible:false,
            addModel:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            rules:{
                username:[
                    {required:true,message:'用户名不能为空'},
                    {max:10,min:3,message:'用户名长度为3-10位'}
                ],
                password:[
                    {required:true,message:'密码不能为空'},
                    {max:15,min:6,message:'用户名长度为6-15位'}
                ],
                email:[
                    {required:true,message:'邮箱不能为空'},
                    {
                        validator(rule,value,callback){
                            if (/^[\w-+\.]+@[\w-+\.]+\.[a-z0-9]+$/i.test(value)){
                                return callback();
                            };
                            callback(new Error('邮箱格式错误'));
                        }
                    }
                ],
                mobile:[
                    {required:true,message:'手机不能为空'},
                     {
                        validator(rule,value,callback){
                            if (/^1[3-9]\d{9}$/.test(value)){
                                return callback();
                            };
                            callback(new Error('手机号格式错误'));
                        }
                    }
                ],
            },
            addLoading:false,
            roleList:[],   //角色列表
            assignVisible:false,  //分配角色是否显示
            roleLoading:false,
            cols,

        }
    },
    computed:{
        isAdd(){
            //如果做编辑的时候，上面有id，就是编辑，如果不是就是添加
            return this.addModel.id ? false : true;
        }
    },
    mounted() {
        
    },
    methods: {
        /**
         * 分配用户角色
         */
        async assignUserRole(){
            try {
                this.addLoading = true;
                await assignRole(this.addModel.id,this.addModel.role_name);
                this.$m.success('角色分配成功');
                this.assignVisible = false;
                this.searchUser();
            } catch (error) {};
            this.addLoading = false;
        },
        async getRoleList(){
            try {
                this.roleList = await getRoles();
                this.roleLoading = true;
            } catch (error) {};
            this.roleLoading = false;
        },
        async delUser(row){
            // let close;
            try {
                await this.$mb.confirm(`您确定要删除【${row.username}】吗？`);
                await deleteUser(row.id);
                this.$m.success('删除成功');
                this.searchUser();
            } catch (error) {
                this.$m.warning('取消删除');
            }
            // close && close;
        },
        /**
         * 渲染
         */
        async searchUser(){
            try{
                this.loading = true;
                const {total,users} = await search(this.queryModel);
                this.list = users;
                this.total = total;
            }catch(error){};
            this.loading = false;
        },
        /**
         * 修改状态
         */
        async changeState(row,value){
            try{
                await switchState(row.id,value);
                this.$m.success('状态变更成功');
                this.searchUser();
            }catch(error){};
        },
        /**
         * 添加用户
         */
        async addUser(){
            try {
                await this.$refs.form.validate();
                this.addLoading = true;
                await (this.isAdd ? user : update )(this.addModel);
                this.$m.success((this.isAdd ? '添加':'修改')+"成功");
                // console.log(this.addModel);
                this.dialogFormVisible = false;
                this.searchUser();
            } catch (error) {};
                this.addLoading = false;
        }

    },
    created(){
        this.searchUser();
    }
}
</script>
<style lang="less">
    .add{
        margin-left: 20px;
    }
</style>